// pages/register/register.js
import {
    fetch
} from "../../utils/util";

const {
    $Toast
} = require('../../dist/base/index');
import {
    registerUser,
    getOpenCode,
    getUserInfo,
    pay,
    getSubject,
    payOrContinue, getSchool,
} from '../../utils/apis';
import {
    getUserInfoUrl
} from "../../utils/urlConfig";

var app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        check: {
            username: false,
            phone: false,
            sex: false,
            birthday: false,
            school: false,
            subject: false
        },
        formData: {
            username: '',
            phone: '',
            sex: 0,
            birthday: '',
            schoolName: '',
            subjectName: '计算机专业',
            school: 1,
            subject: 1,
        },
        sex: [{
            id: 0,
            name: '男'
        }, {
            id: 1,
            name: '女'
        },],
        success: false,
        birthdayEnd: (new Date()).getDate(),
        schoolList: [{
            name: '西北大学',
            id: 1
        }, {
            name: '西安电子科技大学',
            id: 2
        }],
        subjectList: [{
            name: '计算机',
            id: 1
        }, {
            name: '文学院',
            id: 2
        }]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.loadSchool();
        // this.loadSubject();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },

    handleSexChange: function ({
                                   detail = {}
                               }) {
        let sex = detail.value;
        this.setData({
            'formData.sex': sex === "男" ? 0 : 1,
            'current': sex
        });
    },
    handleNumberChange: function ({
                                      detail = {}
                                  }) {
        let phone = detail.detail.value;
        this.setData({
            'check.phone': !(/^1[34578]\d{9}$/.test(phone)),
            'formData.phone': phone
        })
    },
    handleNameChange: function ({
                                    detail = {}
                                }) {
        this.setData({
            'formData.username': detail.detail.value
        })
    },
    handleBirthdayChange: function ({
                                        detail
                                    }) {
        this.setData({
            'formData.birthday': detail.value
        })
    },
    handleSchoolChange: function ({
                                      detail: {
                                          value
                                      }
                                  }) {
        this.setData({
            'formData.school': this.data.schoolList[value].id,
            'formData.schoolName': this.data.schoolList[value].name
        })
    },
    handleSubjectChange: function ({
                                       detail: {
                                           value
                                       }
                                   }) {
        this.setData({
            'formData.subject': this.data.subjectList[value].id,
            'formData.subjectName': this.data.subjectList[value].name
        });
    },
    handleClick: function () {
        // 数据校验
        for (let key in this.data.formData) {
            let item = this.data.formData[key];
            if (item === undefined || item === null || item === '') {
                this.data.check[key] = true;
                $Toast({
                    content: '请正确填写内容' + key,
                    type: 'error',
                    duration: 3,
                    mask: true
                });
                return;
            }
        }
        // 请求服务
        var that = this;
        wx.login({
            success(res) {
                if (res.code) {
                    getOpenCode({
                        code: res.code,
                        success: (response) => {
                            var wxInfo = wx.getStorageSync('wxUserInfo');
                            var data = Object.assign(that.data.formData, {
                                open_code: JSON.parse(response).openid,
                                avatar: wxInfo.avatarUrl,
                                nickname: wxInfo.nickName
                            });
                            var openCode = JSON.parse(response).openid;

                            registerUser({
                                data,
                                success: (response) => {
                                    fetch({
                                        url: getUserInfoUrl,
                                        data: {
                                            openCode
                                        },
                                        success(userInfo) {
                                            app.globalData.loginInfo = userInfo;
                                            pay({
                                                params: {
                                                    total_fee: 4.9,
                                                    uid: app.globalData.loginInfo.id,
                                                    openid: openCode
                                                },
                                                success: function (res) {
                                                    $Toast({
                                                        content: '付款成功',
                                                        type: 'success'
                                                    });
                                                },
                                                fail: function (res) {
                                                    $Toast({
                                                        content: '付款失败',
                                                        type: 'error'
                                                    });
                                                },
                                                complete: function (res) {
                                                    wx.switchTab({
                                                        url: '/pages/index/index',
                                                        success: function (e) {
                                                            let pages = getCurrentPages();
                                                            for (let page of pages) {
                                                                if (page['route'] === 'pages/index/index') {
                                                                    page.onLoad();
                                                                }
                                                            }
                                                        }
                                                    });
                                                }
                                            })
                                        }
                                    });
                                },
                                error: (err) => {
                                    $Toast({
                                        content: '注册失败',
                                        type: 'error',
                                        duration: 2,
                                        mask: true
                                    });
                                }
                            });
                        }
                    })
                } else {
                    $Toast({
                        content: '网络错误',
                        type: 'warning'
                    });
                }
            }
        });


    },
    loadSchool() {
        let that = this;
        if (!app.globalData.schoolList || JSON.stringify(app.globalData.schoolList)) {
            getSchool({
                data: {},
                success: function (schools) {
                    app.globalData.schoolList = schools;
                    that.setData({
                        'schoolList': app.globalData.schoolList
                    });
                }
            });
        }

    },
    loadSubject() {
        var that = this;
        getSubject({
            data: {},
            success: function (subjects) {
                that.setData({
                    'subjectList': subjects
                })
            }
        })
    }
});